/**
 * Created with Vim7.3 ubuntu12.04
 * @fileOverview : 
 * @author : Lyle <lylechen2014@gmial.com>
 * @since : 2014-11-25 13:16:21
 * @filename : app.js
 * @version : 
 * @description : 
 */

define(function(require, exports, module) {

    require("bootstrap/3.3.0/css/bootstrap.min.css"); 
    require("{resourceUrl}css/index.css"); 
    require('backbone'); 
    require('util');
    require('share');
    require('date');
    require('bootstrap'); 
    require('md5/md5');
    require("date/Pikaday/pikaday.css"); 

    var router = Backbone.Router.extend({
    
        cacheObj : {},
    
        prevObj : null,

        currentModule : null,

        initialize: function(options) {
            var tthis = this;
            this.route(/.*/, "routerA", function(){tthis.routeUrl('index','w')});
            this.route(":name/:type", "routerB", function(name,type){tthis.routeUrl(name,type)});
            this.route(":name/:type/:val", "routerC", function(name,type,val){tthis.routeUrl(name,type,val)});
        },

        routeUrl : function(name,type,val) {
            var obj = {
                    name : name,
                    type : type,
                    val  : val
                };
            this.dispatcher(obj); 
        },

        dispatcher : function(obj) {
            var tthis = this;
            this.routesDoFuncBefore(obj);
            if (this.cacheObj[obj.name]) {
                this.cacheObj[obj.name].run(obj); 
                this.currentModule = obj.name;
            } else {
                seajs.moduleUI = '';
                require.async('{controller}'+obj.name,function(module){
                    if (module) {
                        tthis.currentModule = obj.name;
                        tthis.cacheObj[obj.name] = new module(obj); 
                    } else {
                        alert('router name is error!');
                    }
                });
            }
        },

        routesDoFuncBefore : function(obj) {
            if ($('.page').length > 30) {
                var id = $('.page').eq(0).attr('id');
                this.delIdPage(id);
            }
            this.prevObj = obj;
            $('.page').hide();
        },

        delIdPage : function(id) {
            if (typeof(this.cacheObj[id]) !== 'undefined') {
                $('body').undelegate('.'+id);
                this.cacheObj[id].undelegateEvents(); 
                delete this.cacheObj[id];
            }
            $('#'+id).remove();
        }
    });

    module.exports = {
        init: function() {            
             Backbone.routerObj = new router();
             Backbone.history.start();         
        }
    };

});
